import {
  DeleteOutlined,
  EditOutlined,
  PlusCircleOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { Button, Flex, Space, Table, Tag, Tooltip } from 'antd';
import { SPACE } from '@/constants/themeConstant.js';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import ModalUtil from '@/utils/modal.js';
import { TableView } from './styles.jsx';

export const CustomTable = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    request
  }));

  const sizeType = props?.size || 'small';

  const [total, setTotal] = useState(0);
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pageSize, setPageSize] = useState(props?.pagination?.pageSize || 10);
  const [pageNo, setPageNo] = useState(props?.pagination?.pageNo || 1);
  const [selectedRows, setSelectedRows] = useState([]);

  useEffect(() => {
    request();
  }, []);

  const request = (page, callback) => {
    if (props?.request) {
      setLoading(true);
      props.request?.(page ?? { pageNo, pageSize }).then(({ data, success, total }) => {
        if (success) {
          setDataList(data);
          setTotal(total || 0);
        }
        setLoading(false);
        callback?.();
      });
    }
  };

  const getOptions = (row) => {
    const options = [];
    if (props?.onRowEdit) {
      options.push(
        <Button
          key="edit-operation"
          type="primary"
          onClick={() => props?.onRowEdit?.(row)}
          size={sizeType}
        >
          编辑
        </Button>
      );
    }
    if (props?.onRowDelete) {
      options.push(
        <Button
          key="delete-operation"
          type="primary"
          danger
          onClick={() => props?.onRowDelete?.(row)}
          size={sizeType}
        >
          删除
        </Button>
      );
    }
    return [<Space key="operations">{options}</Space>];
  };

  return (
    <>
      <TableView>
        <div className="table-header">
          <Flex className="table-header-title" gap={SPACE} align="center">
            {props?.title}
            {selectedRows.length > 0 && <Tag color="red">{`已选择 ${selectedRows.length} 项`}</Tag>}
          </Flex>
          <div className="table-header-toolbar">
            <Flex gap={SPACE}>
              {props?.toolbar}
              <Tooltip title="刷新">
                <ReloadOutlined
                  className={loading ? 'disabled' : ''}
                  onClick={() => {
                    request(undefined, () => {
                      ModalUtil.msgSuccess('刷新成功');
                    });
                  }}
                />
              </Tooltip>
              {props?.onEdit && (
                <Tooltip title="编辑">
                  <EditOutlined
                    className={
                      selectedRows.length !== 1
                        ? 'disabled'
                        : props?.editDisabled === true
                          ? 'disabled'
                          : ''
                    }
                    onClick={
                      selectedRows.length !== 1
                        ? undefined
                        : props?.editDisabled === true
                          ? undefined
                          : () => props.onEdit(selectedRows[0])
                    }
                  />
                </Tooltip>
              )}
              {props?.onAdd && (
                <Tooltip title="新增">
                  <PlusCircleOutlined
                    className={props?.addDisabled === true ? 'disabled' : ''}
                    onClick={props?.addDisabled === true ? undefined : props.onAdd}
                  />
                </Tooltip>
              )}
              {props?.onDelete && (
                <Tooltip title="删除">
                  <DeleteOutlined
                    className={
                      selectedRows.length < 1
                        ? 'disabled'
                        : props?.deleteDisabled === true
                          ? 'disabled'
                          : ''
                    }
                    disabled
                    onClick={
                      selectedRows.length < 1
                        ? undefined
                        : props?.deleteDisabled === true
                          ? undefined
                          : () => props.onDelete(selectedRows)
                    }
                  />
                </Tooltip>
              )}
            </Flex>
          </div>
        </div>
        <Table
          rowKey={props.rowKey}
          bordered={props.bordered}
          dataSource={dataList}
          size={sizeType}
          loading={loading}
          rowSelection={{
            ...props?.rowSelection,
            selectedRowKeys: selectedRows.map((row) => row[props.rowKey]),
            onChange: (selectedRowKeys, selectedRows, info) => {
              setSelectedRows(selectedRows);
              if (props?.rowSelection && props?.rowSelection?.onChange) {
                props.rowSelection.onChange(selectedRowKeys, selectedRows, info);
              }
            }
          }}
          columns={[
            ...props.columns,
            props?.onRowEdit || props?.onRowDelete
              ? {
                  title: '操作',
                  key: 'operations',
                  width: props.optionsWidth,
                  render: (_dom, row) => getOptions(row)
                }
              : null
          ]}
          pagination={{
            pageSize: pageSize,
            current: pageNo,
            total: total,
            showQuickJumper: true,
            hideOnSinglePage: true,
            showTotal: (total, range) => {
              return `当前页 ${range[0]}-${range[1]}/共 ${total} 条`;
            },
            pageSizeOptions: ['10', '15', '20', '25', '50', '100'],
            onChange: (pageNo, pageSize) => {
              setPageNo(pageNo);
              setPageSize(pageSize);
              request({
                pageNo,
                pageSize
              });
            }
          }}
        >
          {props.children}
          {(props?.onRowEdit || props?.onRowDelete) && (
            <Table.Column
              title="操作"
              key="operations"
              width={props.optionsWidth}
              render={(_dom, row) => getOptions(row)}
            />
          )}
        </Table>
      </TableView>
    </>
  );
});
